<?php

namespace app\lib\exception;

use think\exception\Handle;
use think\Request;
use think\Log;
//需要继承PHP Exception 基类
use Exception;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;

    /**
     * @param Exception $e
     * @return \think\Response|\think\response\Json
     */
    public function render(Exception $e)
    {
        if ($e instanceof BaseException)
        {
            //属于我们抛出的错误内容
            $this->code      = $e->code;
            $this->msg       = $e->msg;
            $this->errorCode = $e->errorCode;
        }
        else{

            //属于系统错误，app_debug开关显示是否需要调试报错内容
            if(config('app_debug')){
                return parent::render($e);
            }

            $this->code      = 500;
            $this->msg       = 'sorry，we make a mistake. (^o^)Y';
            $this->errorCode = 9999;
            $this->recordErrorLog($e);
        }

        $request = Request::instance();
        $result = [
            'msg'         => $this->msg,
            'code'       => $this->errorCode,
            'request_url' => $request = $request->url()
        ];
        return json($result, $this->code);
    }


    /*
     * 将异常写入日志
     */
    private function recordErrorLog(Exception $e)
    {
        Log::init([
            'type'  =>  'File',
            'path'  =>  LOG_PATH,
            'level' => ['error']
        ]);
      //  Log::record($e->getTraceAsString());
        Log::record($e->getMessage(),'error');
    }
}